package com.example.piece.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.example.base.aop.login.LoginCallback
import com.example.base.aop.permission.PermissionRequest
import com.example.base.broadcast.Event
import com.example.base.ext.getViewModel
import com.example.base.ext.toast
import com.example.base.ui.activity.BaseActivity
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.databinding.ActivityMainBinding
import com.example.piece.tools.SIMCardInfo
import com.example.piece.ui.fragment.HomeFragment
import com.example.piece.ui.fragment.MessageFragment
import com.example.piece.ui.fragment.UserFragment
import com.example.piece.ui.fragment.VideoFragment
import com.example.piece.vm.UserViewModel
import xyz.doikki.videoplayer.player.VideoViewManager

/**
 * 首页
 */
class MainActivity : BaseActivity<ActivityMainBinding>() {
    override val isTransparentStatusBar: Boolean = true

    override val isDarkMode: Boolean = true
    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }

    override fun isRegisterEventBus(): Boolean {
        return true
    }

    private lateinit var homeFragment: Fragment
    private lateinit var videoFragment: Fragment
    private lateinit var messageFragment: Fragment
    private lateinit var userFragment: Fragment

    override fun getContentRes(): Int = R.layout.activity_main
    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        homeFragment = HomeFragment.newInstance()
        addFragment(R.id.fl_main, homeFragment)
        videoFragment = VideoFragment.newInstance()
        addFragment(R.id.fl_main, videoFragment)
        messageFragment = MessageFragment.newInstance()
        addFragment(R.id.fl_main, messageFragment)
        userFragment = UserFragment.newInstance()
        addFragment(R.id.fl_main, userFragment)
        mBinding.llMainTab0.setOnClickListener {
            chooseTab(R.id.rb_mainTab0)
        }
        mBinding.llMainTab1.setOnClickListener {
            chooseTab(R.id.rb_mainTab1)

        }
        mBinding.llMainTab2.setOnClickListener {
            chooseTab(R.id.rb_mainTab2)

        }
        mBinding.llMainTab3.setOnClickListener {
            chooseTab(R.id.rb_mainTab3)

        }
        mBinding.llMainTab4.setOnClickListener {
            chooseTab(R.id.rb_mainTab4)

        }

        chooseTab(R.id.rb_mainTab0)

    }

    fun chooseTab(checkedId: Int) {
        runOnUiThread {
            getVideoViewManager()?.releaseByTag(Key.DataKey.HOME_LIST)

        }
        when (checkedId) {
            R.id.rb_mainTab0 -> {
                mBinding.rgMainTab.setBackgroundColor(resources.getColor(R.color.white))
                //   mBinding.flMain.setBackgroundColor(resources.getColor(R.color.white))
                mBinding.ll.setBackgroundColor(resources.getColor(R.color.white))

                mBinding.rbMainTab0.isSelected = true
                setTabSelect(false, mBinding.rbMainTab0, mBinding.rbMainTab1,
                    mBinding.rbMainTab2,
                    mBinding.rbMainTab3,
                    mBinding.rbMainTab4)
                setTabSelectImg(false, mBinding.rbMainTab00, mBinding.rbMainTab11,
                    mBinding.rbMainTab22,
                    mBinding.rbMainTab33,
                    mBinding.rbMainTab44)

                hideAllFragment(videoFragment, messageFragment, userFragment)

                showFragment(homeFragment)


            }
            R.id.rb_mainTab1 -> {
                mBinding.rbMainTab1.isSelected = true
                mBinding.rgMainTab.setBackgroundColor(resources.getColor(R.color.black))
                //     mBinding.flMain.setBackgroundColor(resources.getColor(R.color.black))
                mBinding.ll.setBackgroundColor(resources.getColor(R.color.black))

                setTabSelect(true, mBinding.rbMainTab1, mBinding.rbMainTab0,
                    mBinding.rbMainTab2,
                    mBinding.rbMainTab3,
                    mBinding.rbMainTab4)
                setTabSelectImg(true, mBinding.rbMainTab11, mBinding.rbMainTab00,
                    mBinding.rbMainTab22,
                    mBinding.rbMainTab33,
                    mBinding.rbMainTab44)
                hideAllFragment(homeFragment, messageFragment, userFragment)

                showFragment(videoFragment)

            }
            R.id.rb_mainTab3 -> {

                jumpTab3()

            }
            R.id.rb_mainTab4 -> {
                mBinding.rbMainTab4.isSelected = true
                mBinding.rgMainTab.setBackgroundColor(resources.getColor(R.color.white))
                //  mBinding.flMain.setBackgroundColor(resources.getColor(R.color.white))
                mBinding.ll.setBackgroundColor(resources.getColor(R.color.white))


                setTabSelect(false, mBinding.rbMainTab4, mBinding.rbMainTab0,
                    mBinding.rbMainTab1,
                    mBinding.rbMainTab2,
                    mBinding.rbMainTab3)
                setTabSelectImg(false, mBinding.rbMainTab44, mBinding.rbMainTab00,
                    mBinding.rbMainTab11,
                    mBinding.rbMainTab22,
                    mBinding.rbMainTab33)
                hideAllFragment(homeFragment, videoFragment, messageFragment)

                showFragment(userFragment)

            }
        }


    }

    @LoginCallback
    private fun jumpTab3() {
       /* if (App.USER_TOKEN.isNullOrEmpty()) {
            val onBindView =
                object :
                    OnBindView<FullScreenDialog>(R.layout.layout_full_login, true) {
                    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
                    override fun onBind(dialog: FullScreenDialog?, v: View?) {
                        val tvPhone = v?.findViewById<EditText>(R.id.edit_userName)
                        v?.findViewById<TextView>(R.id.tv_getCode)//获取验证码
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userLoginGetCode(
                                        this@MainActivity,
                                        tvPhone?.text.toString()
                                    ) {
                                        toast(it.msg)
                                    } onError {
                                        toast(it)

                                    }
                                } else {
                                    toast("请输入手机号码！")
                                }

                            }
                        v?.findViewById<TextView>(R.id.tv_loginByOwenPhone)
                            ?.setOnClickListener {
                                getOwnPhone(tvPhone)
                            }

                        val etPsd = v?.findViewById<TextView>(R.id.edit_password)

                        v?.findViewById<ImageView>(R.id.img_qq)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    userViewModel.userPswReset(
                                        this@MainActivity,
                                        etPsd?.text.toString(), "111sam111",
                                        tvPhone?.text.toString()
                                    ) {
                                        toast(it.msg)
                                    } onError {
                                        toast(it)

                                    }
                                } else {
                                    toast("请输入手机号码！")
                                }
                            }
                        v?.findViewById<TextView>(R.id.btn_submit)
                            ?.setOnClickListener {
                                if (!tvPhone?.text.isNullOrEmpty()) {
                                    if (!etPsd?.text.isNullOrEmpty()) {
                                        userViewModel.userLoginCode(
                                            this@MainActivity,
                                            etPsd?.text.toString(),
                                            tvPhone?.text.toString()
                                        ) {
                                            if (it.code === 200) {
                                                App.USER_TOKEN = it.data.token
                                                //存本地token
                                                ConfigTool.putString(Key.DataKey.TOKEN,
                                                    it.data.token)
                                                //登录成功
                                                EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))

                                                mBinding.rbMainTab3.isSelected = true
                                                setTabSelect(false,
                                                    mBinding.rbMainTab3,
                                                    mBinding.rbMainTab0,
                                                    mBinding.rbMainTab1,
                                                    mBinding.rbMainTab2,
                                                    mBinding.rbMainTab4)

                                                setTabSelectImg(false,
                                                    mBinding.rbMainTab33,
                                                    mBinding.rbMainTab00,
                                                    mBinding.rbMainTab11,
                                                    mBinding.rbMainTab22,
                                                    mBinding.rbMainTab44)
                                                hideAllFragment(homeFragment,
                                                    videoFragment,
                                                    userFragment)
                                                showFragment(messageFragment)
                                                dialog?.dismiss()
                                            }
                                        } onError {
                                            toast(it)

                                        }
                                    } else {
                                        toast("请输入验证码！")

                                    }

                                } else {
                                    toast("请输入手机号码！")
                                }
                            }


                        val spannableStringBuilder = SpannableStringBuilder()
                        //设置文字
                        spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
                        //设置文字点击事件（用户协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "用户协议",

                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                        //设置文字点击事件（隐私协议）
                        spannableStringBuilder.setSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                navigationTo(
                                    RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                        Key.DataKey.H5_TITLE to "隐私协议",
                                        Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                    )
                                )
                            }
                        }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        //设置颜色
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        spannableStringBuilder.setSpan(
                            ForegroundColorSpan(
                                Color.parseColor(
                                    "#46AFFF"
                                )
                            ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )


                        val tvXieYi = v?.findViewById<TextView>(R.id.tv_xieyi)
                        tvXieYi?.movementMethod = LinkMovementMethod.getInstance()
                        tvXieYi?.text = spannableStringBuilder

                    }

                }
            FullScreenDialog.show(onBindView).dialogLifecycleCallback = object :
                DialogLifecycleCallback<FullScreenDialog>() {
                override fun onDismiss(dialog: FullScreenDialog?) {

                    super.onDismiss(dialog)

                }

                override fun onShow(dialog: FullScreenDialog?) {
                    super.onShow(dialog)
                }

            }


        } else {*/
            mBinding.rbMainTab3.isSelected = true
            mBinding.rgMainTab.setBackgroundColor(resources.getColor(R.color.white))
            // mBinding.flMain.setBackgroundColor(resources.getColor(R.color.white))
            mBinding.ll.setBackgroundColor(resources.getColor(R.color.white))

            setTabSelect(false, mBinding.rbMainTab3, mBinding.rbMainTab0,
                mBinding.rbMainTab1,
                mBinding.rbMainTab2,
                mBinding.rbMainTab4)
            setTabSelectImg(false, mBinding.rbMainTab33, mBinding.rbMainTab00,
                mBinding.rbMainTab11,
                mBinding.rbMainTab22,
                mBinding.rbMainTab44)
            hideAllFragment(homeFragment, videoFragment, userFragment)

            showFragment(messageFragment)
        //}
    }

    fun setTabSelect(isVideo: Boolean, vararg views: View) {
        if (isVideo) {
            mBinding.imgAdd.setImageResource(R.drawable.ic_push_white)
        } else {
            mBinding.imgAdd.setImageResource(R.drawable.ic_push)

        }
        for ((index, view) in views.withIndex()) {
            if (isVideo) {

                val textView = view as TextView
                textView.setTextColor(resources.getColor(R.color.white))
            } else {

                val textView = view as TextView

                textView.setTextColor(resources.getColorStateList(R.drawable.selector_color_red_black) as ColorStateList)


            }
            view.isSelected = index == 0

        }
    }

    fun setTabSelectImg(isVideo: Boolean, vararg views: View) {

        for ((index, view) in views.withIndex()) {
            if (index == 0) {
                val animation: Animation = AnimationUtils.loadAnimation(
                    this,
                    R.anim.anim_button)
                view.startAnimation(animation)
            }
            if (isVideo) {

                val textView = view as ImageView
                textView.setColorFilter(resources.getColor(R.color.white),
                    PorterDuff.Mode.SRC_ATOP)
            } else {

                val textView = view as ImageView
                textView.setColorFilter(resources.getColor(R.color.white),
                    PorterDuff.Mode.DST)


            }
            view.isSelected = index == 0

        }
    }

    //获取本机号码
    @SuppressLint("MissingPermission")
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    @PermissionRequest(
        value = [
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_PHONE_NUMBERS,
            Manifest.permission.READ_SMS
        ]
    )

    fun getOwnPhone(phone: TextView?) {
        val phoneNumbers =
            SIMCardInfo(this@MainActivity).phoneNumberS
        if (phoneNumbers.isNotEmpty()) {
            for (it in phoneNumbers) {

            }
            phone?.text = phoneNumbers[0]

        } else {
            toast("暂未获取到手机号")
        }


    }

    override fun receiveEvent(event: Event<Any>?) {
        super.receiveEvent(event)
        when (event?.code) {
            Key.EventKey.EVENT_UNREAD_NUM -> {//未读信息数量
                if ("0" == event.data as String) {
                    mBinding.tvRead.visibility = View.GONE
                } else {
                    mBinding.tvRead.visibility = View.VISIBLE

                }
                mBinding.tvRead.text = event.data as String
            }

        }
    }

    override fun onBackPressed() {

        if (getVideoViewManager()!!.onBackPress(Key.DataKey.HOME_LIST)) return
        super.onBackPressed()
    }

    private fun getVideoViewManager(): VideoViewManager? {
        return VideoViewManager.instance()
    }
}
